#!/bin/python
import SocketServer
import logging
import socket
import itertools
import random
import math

log = logging.getLogger('prep-conf')


def sniffPort(portnum):
    try:
        server = SocketServer.TCPServer(("", portnum), None)
    except:
        return False
    else:
        return True
    
def findPorts(initialPort = 5324):
    port = initialPort
    while True:
        log.debug("sniffing port: "+str(port))
        if sniffPort(port):
            if sniffPort(port + 1):
                return port
            else:
                port = port + 2 # next port busy
        else:
            port = port + 1

def loadhosts(hostfilename="hosts.txt"):
    hosts = []
    hostfile = open(hostfilename)
    for host in hostfile:
        hosts.append(host.strip())
    hostfile.close()
    return hosts

def generateSenddelaytime(hostnum, timespan, s = 0.5):
    import numpy.random
    numpy.random.seed(1235)
    
    sampleNum = 1000
    hitcount = [ 0 for i in range (0, hostnum) ]
    for i in range(0, sampleNum):
        hitcount[int(0.5 + numpy.random.pareto(0.5)) % hostnum] += 1
    log.debug("hits: "+str(hitcount))
    senddelaytime = [ timespan / float(max(1, hits)) for hits in hitcount ]
    log.debug("senddelay: "+str(senddelaytime))
    return senddelaytime


def writeSenddelaytime(hosts, outfile, fileCreated = False):
    try:
        senddelayfile = open("senddelay.txt")
        for line in senddelayfile:
            outfile.write(line)
        senddelayfile.close()
    except IOError:
        if fileCreated:
            log.error("created the file, but can't open again")
            raise
        
        senddelaytime=generateSenddelaytime(len(hosts), 100.0)
        senddelayfile = open("senddelay.txt", "w")
        for (time,host) in itertools.izip(senddelaytime,hosts):
            senddelayfile.write("senddelay,"+str(host)+" = "+str(time)+"\n")
        senddelayfile.close()
        writeSenddelaytime(hosts, outfile, True)

def appendFile(filename, outfile):
    inf = open(filename)
    for line in inf:
        outfile.write(line)
    inf.close()


    
if __name__=="__main__":
    
    logging.basicConfig(level=logging.DEBUG)
    conf = open("config.txt", "w")

    hostname = str(socket.gethostname())
    log.info("my hostname: "+hostname)
    conf.write("myid = "+hostname+"\n")
    
    port = findPorts(5155)
    log.info("my port: "+str(port))
    conf.write("myport = "+str(port)+"\n")

    conf.write("connectionnode=planetlab4.singaren.net.sg\n")
    conf.write("connectionport=5155\n")
    conf.write("sendfile=book.txt\n")

    hosts = loadhosts()
    permhosts = hosts[:]
    random.shuffle(permhosts)
    writeSenddelaytime(permhosts, conf)
    appendFile("initsleep.txt", conf)
    appendFile("hostcosts.txt", conf)
    
    conf.close()
    
